<template>
  <div>
    <h1>订单列表</h1>
    <div>
      <el-form :inline="true" :model="searForm" class="demo-form-inline">
        <el-form-item label="关键字/Id/商品">
          <el-input
            v-model="searForm.keyWord"
            placeholder="请输入关键字/Id/商品"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searForm.statusId"
            placeholder="请选择状态"
            style="width: 140px"
            clearable
          >
            <el-option label="未下单" :value="0" />
            <el-option label="已下单" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="searForm.typeId"
            placeholder="请选择类型"
            style="width: 140px"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :label="item.dictName"
              :value="item.dictValue"
              :key="item.dictType"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadOrderList()">查询</el-button>
          <el-button type="success" @click="onAddOrder()">添加订单</el-button>
          <el-button type="success" @click="onExcelOrder()">导出</el-button>
          <el-button type="danger" @click="ondeletebatchByOrder()"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="orderData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        ref="multipleTableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderId" label="Id" />
        <el-table-column prop="orderNo" label="编号" />
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="scope">
            <span v-if="scope.row.orderStatus == 0">未下单</span>
            <span v-if="scope.row.orderStatus == 1">已下单</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderAmount" label="订单金额" />
        <el-table-column prop="payTime" label="支付时间" />
        <el-table-column prop="orderType" label="订单类型">
          <template #default="scope">
            <span v-if="scope.row.orderType == 1">普通订单</span>
            <span v-if="scope.row.orderType == 2">秒杀订单</span>
          </template>
        </el-table-column>
        <el-table-column prop="prodInfo" label="商品" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" />
      </el-table>
    </div>
    <div>
      <el-pagination
        v-model:current-page="searForm.pageNum"
        v-model:page-size="searForm.pageSize"
        :page-sizes="[2, 3, 4, 5]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加订单" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item label="商品" :label-width="formLabelWidth">
            <el-select v-model="form.infoId" placeholder="请选择商品">
              <el-option
                v-for="item in prodInfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" :label-width="formLabelWidth">
            <el-input v-model="form.buyNum" />
          </el-form-item>
          <el-button type="success" @click="selectProdInfo()"
            >添加订单</el-button
          >
          <el-table :data="form.infoList" border style="width: 100%">
            <el-table-column prop="infoId" label="Date" />
            <el-table-column prop="prodSku" label="Name" />
            <el-table-column prop="prodName" label="Address" />
            <el-table-column prop="prodPrice" label="Address" />
            <el-table-column prop="buyNum" label="Address" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="danger" @click="ondelete(scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div>
            <span>{{ form.amount }}</span>
          </div>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onAddSubmitOrder(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getOrderList,
  getDictList,
  deleteBatchByOrderId,
  getProdInfo,
  addOrder,
} from "../api/api";
import { ElMessage, type TableInstance } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<any[]>([]);
const orderData = ref([]);
const prodInfoList = ref([]);
const total = ref(0);
const typeList = ref([]);
const searForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
  statusId: null,
  typeId: null,
});
const rules = ref<FormRules>({
  infoList: [{ required: true, message: "商品详情不能为空", trigger: "blur" }],
});
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
  infoId: null,
  infoList: [],
  buyNum: null,
  amount: 0.0,
});

const loadOrderList = () => {
  getOrderList(searForm.value).then((res) => {
    if (res.data.code == 200) {
      orderData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

//分页信息
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searForm.value.pageSize = val;
  loadOrderList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searForm.value.pageNum = val;
  loadOrderList();
};

//批量删除
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const ondeletebatchByOrder = () => {
  deleteBatchByOrderId(multipleSelection.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      loadOrderList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//回显商品
const selectProdInfo = () => {
  form.value.amount = 0.0;
  prodInfoList.value.forEach((item) => {
    if (item.infoId == form.value.infoId) {
      item.buyNum = form.value.buyNum;
      form.value.infoList.push(item);
    }
  });
  onjsamount();
  form.value.infoId = null;
  form.value.buyNum = null;
};
//移除商品详情
const ondelete = (row: any) => {
  form.value.amount = 0.0;
  form.value.infoList.forEach((item, index) => {
    if (item.infoId === row.infoId) {
      form.value.infoList.splice(index, 1);
    }
  });
  onjsamount();
};
const onjsamount = () => {
  form.value.infoList.forEach((it) => {
    form.value.amount += it.buyNum * it.prodPrice;
  });
};
//去添加订单
const onAddOrder = () => {
  form.value = {
    infoId: null,
    infoList: [],
    buyNum: null,
    amount: 0.0,
  };
  dialogFormVisible.value = true;
};
//添加
const onAddSubmitOrder = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addOrder(form.value.infoList).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadOrderList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//导出
const onExcelOrder = () => {
  let url = "http://localhost:9011//prod/order/uploadExout/" + userId.value;
  window.open(url);
};
//页面钩子函数
const userId = ref(0);
onMounted(() => {
  let u = sessionStorage.getItem("user");
  if (u != null) {
    let user = JSON.parse(u);
    userId.value = user.userId;
  }

  getProdInfo().then((res) => {
    if (res.data.code == 200) {
      prodInfoList.value = res.data.data;
    }
  });
  getDictList(4).then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
  loadOrderList();
});
</script>

<style scoped></style>
